package edu.vt.ece4564.bluetendance.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DatabaseConnector {
	private static DatabaseConnector databaseConnector = new DatabaseConnector();
	Connection connection = null;
	public String commandText;
	
	private DatabaseConnector() {
		try {
			Class.forName(DatabaseStrings.driver).newInstance();
			connection = DriverManager.getConnection(DatabaseStrings.databaseURL + DatabaseStrings.databaseName, DatabaseStrings.username, DatabaseStrings.password);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Error while creating database connection.");
		}
	}

	public static DatabaseConnector get() {
		return databaseConnector;
	}
	
	public ResultSet executeQuery() {
		Statement stmt;
		ResultSet queryResult = null;
		try {
			stmt = connection.createStatement();
			queryResult = stmt.executeQuery(commandText);
		} catch (SQLException e) {
			System.out.println("Error while executing statment: " + commandText);
		}
		return queryResult;
	}
	
	public int executeNonQuery() {
		try {
			Statement statement = connection.createStatement();
			statement.execute(commandText);
			return statement.getUpdateCount();
		} catch (SQLException e) {
			return 0;
		}
	}
	
	/**
	 * Helper method to return a list of all the strings in a specified ResultSet
	 * @param results the ResultSet to get the strings from
	 */
	public List<String> getQueryResultsList(ResultSet results) {
		List<String> resultStrings = new ArrayList<String>();
		
		try {
			while (results.next()) {
				resultStrings.add(results.getString(1));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return resultStrings;
	}
	
	/**
	 * Close the database connection
	 */
	public void closeConnection() {
		try {
			connection.close();
		} catch (SQLException e) {
			System.out.println("Error while closing database connection.");
		}
	}
}
